#include <brpc/channel.h>
#include <thread>
#include "main.pb.h"
#include "../../common/channel.hpp"

//异步调用的回调函数：处理服务端响应
void callback(brpc::Controller* cntl, ::example::EchoResponse* response) {
    //自动释放资源（避免内存泄漏）
    std::unique_ptr<brpc::Controller> cntl_guard(cntl);
    std::unique_ptr<example::EchoResponse> resp_guard(response);
    
    //检查调用是否失败
    if (cntl->Failed()) {
        std::cout << "Rpc调用失败：" << cntl->ErrorText() << std::endl;
        return;
    }

    //打印正常响应
    std::cout << "收到响应: " << response->message() << std::endl;
}

int main(int argc, char *argv[]) {
    //初始化Brpc信道（链接服务端）
    brpc::ChannelOptions options;
    options.connect_timeout_ms = 1; //链接无超时
    options.timeout_ms = -1;        //调用无超时
    options.max_retry = 3;          //失败重试3次
    options.protocol = "baidu_std"; //使用BRPC默认协议
    brpc::Channel channel;
    int ret = channel.Init("127.0.0.1:8080", &options); //连接本地8080端口
    if (ret == -1) {
        std::cout << "初始化信道失败！\n";
        return -1;
    }

    //创建客户端存根（用于调用服务）
    example::EchoService_Stub stub(&channel);

    //构造请求消息
    example::EchoRequest req;
    req.set_message("hello~world~！");

    //异步调用Echo方法
    brpc::Controller* cntl = new brpc::Controller(); //控制调用过程（如超时,错误）
    example::EchoResponse* rsp = new example::EchoResponse();// 接收响应
    //创建回调：调用完成后执行callback函数
    auto closure = google::protobuf::NewCallback(callback, cntl, rsp);

    // stub.Echo(cntl, &req, rsp, closure); //异步调用
    // std::cout << "异步调用结束！\n";

    stub.Echo(cntl, &req, rsp, nullptr); //同步调用
    if (cntl->Failed()) {
        std::cout << "RPC调用失败：" << cntl->ErrorText() << std::endl;
        return -1;
    }
    std::cout << "收到响应: " << rsp->message() << std::endl;
    delete cntl;
    delete rsp;

    
    std::this_thread::sleep_for(std::chrono::seconds(3));
    return 0;
}